package com.shiwaixiangcun.customer.module.intelligent

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterShareCamera
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CameraShareInfo
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.entity.DeviceBaseListEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.ResponseConfig.SUCCESS
import com.shiwaixiangcun.customer.network.ResponseConfig.TOKEN_INVALID
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil
import kotlinx.android.synthetic.main.activity_share_camera.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 分享智能设备
 */
class ShareCameraActivity : BaseActivity() {


    val REQUEST_DATA = 10
    var isEmpty = false
    private var viewEmpty: View? = null
    var mAdapter: AdapterShareCamera? = null
    var mList: ArrayList<CameraShareInfo>? = null
    var strToken: String = ""
    var refreshToken: String = ""
    private var cameraId: String = ""
    var channelId: Int = 0
    private var tvAddShare: TextView? = null
    var headView: View? = null
    var tvNumberDevice: TextView? = null
    private var bundle: Bundle? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_share_camera)
        EventUtil.getInstance().register(this)
        initBundleData()
        initData()
        initView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.SHARE_LIST) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_DATA -> {
                var list = simpleEvent.data as MutableList<CameraShareInfo>
                if (list.size == 0) {
                    layout_add_account.visibility = View.GONE
                    mAdapter?.emptyView = viewEmpty

                } else {
                    mList?.clear()
                    mList?.addAll(list)
                    tvNumberDevice!!.text = "已将设备分享给${mList?.size}名用户"
                    mAdapter?.addHeaderView(headView)
                    mAdapter?.notifyDataSetChanged()

                }
            }
        }

    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }


    override fun onPause() {
        super.onPause()
        EventUtil.getInstance().unregister(this)
    }

    private fun initBundleData() {
        cameraId = intent.extras.getString("deviceId")
        channelId = intent.extras.getInt("channelId")
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        refreshToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String
    }

    private fun initData() {


        mAdapter?.notifyDataSetChanged()
        OkGo.get<String>(GlobalApi.shareList)
                .params("access_token", strToken)
                .params("deviceId", cameraId)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseListEntity<CameraShareInfo>>() {}.type
                        val responseEntity = Gson().fromJson<DeviceBaseListEntity<CameraShareInfo>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.SHARE_LIST, REQUEST_DATA, responseEntity.data))
                            }
                        }
                    }
                })
    }

    private fun initView() {
        bundle = Bundle()
        bundle?.putString("deviceId", cameraId)
        bundle?.putInt("channelId", channelId)
        mList = ArrayList()
        mAdapter = AdapterShareCamera(mList)

        tv_page_name.text = "分享设备"
        viewEmpty = layoutInflater.inflate(R.layout.layout_empty_share_camera, null, false)
        headView = layoutInflater.inflate(R.layout.layout_device_header, null, false)
        tvNumberDevice = headView?.findViewById(R.id.tv_list_header)
        tvAddShare = viewEmpty?.findViewById(R.id.tv_add_share)

        mList?.clear()
        mAdapter?.notifyDataSetChanged()
        rv_share_camera.layoutManager = LinearLayoutManager(this)
        rv_share_camera.adapter = mAdapter
        mAdapter?.setOnItemChildClickListener { adapter, _, position ->

            val item = adapter?.getItem(position) as CameraShareInfo
            val cancelShare = DialogLoginOut(mContext, R.layout.item_dialog_loginout)
            cancelShare.setTitle("你确定取消该分享么？")
            cancelShare.setMessage("")
            cancelShare.setYesOnclickListener("取消分享") {
                cancelShare(item.customerId, item.deviceId)

                cancelShare.dismiss()
            }
            cancelShare.setNoOnclickListener("取消") { cancelShare.dismiss() }
            cancelShare.show()


        }
        val divider = RecyclerViewDivider.Builder(this)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.END)
                .setMarginLeft(20f)
                .setColorRes(R.color.color_divider_0_3)
                .build()
        rv_share_camera.addItemDecoration(divider)
        layout_add_account.setOnClickListener {
            readyGo(AddShareActivity::class.java, bundle)
        }
        tvAddShare?.setOnClickListener {
            Log.e(BUG_TAG, "点击分享")
            readyGo(AddShareActivity::class.java, bundle)
        }



        back_left.setOnClickListener { finish() }


    }

    /**
     * 取消分享
     */
    private fun cancelShare(customerId: Long, deviceId: String) {
        OkGo.delete<String>(GlobalApi.cancelShare)
                .params("customerId", customerId)
                .params("deviceId", deviceId)
                .params("access_token", strToken)
                .isSpliceUrl(true)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        showToastShort("取消分享失败")
                    }
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<Any>>() {}.type
                        val responseEntity = Gson().fromJson<DeviceBaseEntity<Any>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            SUCCESS -> {
                                showToastShort("取消分享成功")
                                initData()
                            }
                            TOKEN_INVALID -> {
                                showToastShort("当前登录失效")
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                            else -> {
                                showToastShort("取消分享失败")
                            }
                        }
                    }
                })
    }
}
